package com.kit.data.kitopeso.analysis.libs

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustAttribution
import com.adjust.sdk.AdjustConfig
import com.adjust.sdk.AdjustEvent
import com.adjust.sdk.LogLevel
import com.google.gson.Gson
import com.kit.data.kitopeso.KitoApp
import com.kit.data.kitopeso.PathMaping
import com.kit.data.kitopeso.base.BaseParams
import com.kit.data.kitopeso.net.U
import com.kit.data.kitopeso.tools.LogUtil
import com.kit.data.kitopeso.tools.SpUtils

object AdjustLib {

    fun fetch(context: Application, onSuccess: (String) -> Unit) {
        try {
            val config = AdjustConfig(context, "ecwsmislwow0", AdjustConfig.ENVIRONMENT_PRODUCTION)
            config.setLogLevel(LogLevel.INFO)
            config.setOnAttributionChangedListener { saveAttribution(it, onSuccess) }

            Adjust.initSdk(config)

            registerAdjustActivityLifecycle(context)

//            val attribution = Adjust.getAttribution()
//            saveAttribution(attribution, onSuccess)

            Adjust.getAttribution { var1 ->
                saveAttribution(var1, onSuccess)
            }

        } catch (e: Exception) {
        }
    }

    fun reFetch(onSuccess: (String) -> Unit) {
//        val attribution = Adjust.getAttribution()
//        saveAttribution(attribution, onSuccess)
        Adjust.getAttribution { var1 ->
            saveAttribution(var1, onSuccess)
        }
    }

    private fun saveAttribution(
        attribution: AdjustAttribution?,
        onSuccess: (String) -> Unit
    ) {
        attribution?.let { result ->

            var costAmount = ""
            if (result.costAmount != null && !result.costAmount.isNaN()) {
                costAmount = result.costAmount.toString();
            }
            val token = SpUtils.get_string(KitoApp.getInstance(), SpUtils.KEY_TOKEN, "")
            Adjust.getAdid { adid ->
                val data = hashMapOf<String, Any>(
                    "product" to U.URL_MAIN_PRODUCT, // TODO: 补充产品名
                    "path" to PathMaping.PathList[64], // TODO: 补充映射
                    "token" to token, // TODO: 补充token
//                    "adid" to result.adid.orEmpty(),
                    "adid" to adid.orEmpty(),
                    "deviceId" to AdIdLib.adId(),
                    "network" to result.network.orEmpty(),
                    "adgroup" to result.adgroup.orEmpty(),
                    "creative" to result.creative.orEmpty(),
                    "costType" to result.costType.orEmpty(),
                    "campaign" to result.campaign.orEmpty(),
                    "clickLabel" to result.clickLabel.orEmpty(),
                    "trackerName" to result.trackerName.orEmpty(),
                    "trackerToken" to result.trackerToken.orEmpty(),
                    "costCurrency" to result.costCurrency.orEmpty(),
                    "fbInstallReferrer" to result.fbInstallReferrer.orEmpty(),
                    "costAmount" to (costAmount),
                    "androidId" to AdIdLib.androidId(),
                    "advertId" to AdIdLib.adId(),
                    "isLimitAdTrackingEnabled" to AdIdLib.adEnabled().toString(),
                    "aduid" to AdIdLib.adId(),
                    "aduidPath" to AdIdLib.androidId(),
                    "version" to BaseParams.getVersion(KitoApp.getInstance()),
                    "apiVersion" to "v3"
                )
                LogUtil.e("me", "AdjustLib data->$data")
                onSuccess.invoke(Gson().toJson(data).trim())
            }
        }
    }

    fun addEvent(event: IEvent) {
        try {
            when (event) {
                IEvent.REGISTER -> {
                    Adjust.trackEvent(AdjustEvent("7oqleb"))
                }

                IEvent.APPLY -> {
                    Adjust.trackEvent(AdjustEvent("3kfgqs"))
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun registerAdjustActivityLifecycle(context: Application) {
        context.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(p0: Activity, p1: Bundle?) {
            }

            override fun onActivityStarted(p0: Activity) {
            }

            override fun onActivityResumed(p0: Activity) {
                Adjust.onResume()
            }

            override fun onActivityPaused(p0: Activity) {
                Adjust.onPause()
            }

            override fun onActivityStopped(p0: Activity) {
            }

            override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
            }

            override fun onActivityDestroyed(p0: Activity) {
            }
        })
    }
}